package baijia

import (
	"errors"
	"fmt"
	_ "net/http/pprof"
	"time"

	"code.whyyou.me/yixiangguo/pub-platform/pub-lib/utils"
	"github.com/astaxie/beego"
	"github.com/chromedp/cdproto"
	"github.com/lauyoume/chromedp"
)

var (
	BAIDU_ARTICLE_CHROME_TIMEOUT = 30
	BAIDU_VIDEO_CHROME_TIMEOUT   = 120
)

func init() {
	BAIDU_ARTICLE_CHROME_TIMEOUT = beego.AppConfig.DefaultInt("baijia::article_chrome_timeout", 300)
	BAIDU_VIDEO_CHROME_TIMEOUT = beego.AppConfig.DefaultInt("baijia::video_chrome_timeout", 300)
}

type TaskEnd struct {
	err error
}

func PubArticleByChrome(ck string, ty string, feeds FeedArticle) error {

	var err error

	id, ok := ChromeCatNameToID(ty)
	if !ok {
		return errors.New("不支持的分类信息：" + ty)
	}

	cdp, err := utils.NewPubChrome()
	if err != nil {
		return err
	}
	defer utils.Close(cdp)

	timeout := time.After(time.Second * time.Duration(BAIDU_ARTICLE_CHROME_TIMEOUT))
	taskEnd := make(chan error)
	go func() {
		taskEnd <- utils.Run(cdp, pubArticleTask(ck, feeds, id))
	}()

	select {
	case <-timeout:
		beego.Error("任务执行超时")
	case err = <-taskEnd:
		beego.Info("任务执行结束:", err)
	}

	return err
}

func PubVideo(ck string, ty string, videoPath string, imagePath string, title string, tag string) error {
	beego.Info("下载视频中...")
	if err := utils.SaveFile(videoPath, "video.mp4"); err != nil {
		return err
	}
	beego.Info("下载视频 完成")
	defer utils.DeleteFile("./video.mp4")
	if err := utils.SaveFile(imagePath, "cover.png"); err != nil {
		return err
	}
	beego.Info("下载封面图 完成")
	defer utils.DeleteFile("./cover.png")

	var err error

	id, ok := ChromeVideoCatNameToID(ty)
	if !ok {
		return errors.New("不支持的分类信息：" + ty)
	}

	cdp, err := utils.NewPubChrome()
	if err != nil {
		beego.Error("chrome 启动失败,error :", err)
		return err
	}
	defer utils.Close(cdp)

	timeout := time.After(time.Second * time.Duration(BAIDU_VIDEO_CHROME_TIMEOUT))
	taskEnd := make(chan error)
	go func() {
		defer func() {
			if r := recover(); r != nil {
				taskEnd <- errors.New("发送未知错误【recover】")
				beego.Error("[recover]", r)
			}
		}()
		taskEnd <- utils.Run(cdp, pubVideo(ck, id, "/video.mp4", "/cover.png", title, tag))
	}()

	select {
	case <-timeout:
		beego.Warning("任务执行超时")
	case err = <-taskEnd:
		beego.Info("任务执行结束")
	}

	return err
}

func pubArticleTask(ck string, article FeedArticle, ty int) chromedp.Tasks {
	jsf := `window.UE.getEditor('ueditor').setContent("%s")`
	content := ""
	for _, feed := range article.Feed {
		if feed.Type == "text" {
			content += ` <p>` + feed.Data + ` </p> <br> `
		}
		if feed.Type == "image" {
			content += fmt.Sprintf(`<p> <img src='%s' ></p> `, feed.Data)
		}
	}

	js := fmt.Sprintf(jsf, content)
	res := []byte{}
	return chromedp.Tasks{
		utils.ActionCookies(`.baidu.com`, ck),
		chromedp.Navigate(`http://baijiahao.baidu.com/builder/article/edit?type=news`),
		chromedp.WaitEvent(cdproto.EventPageLoadEventFired),
		chromedp.WaitVisible("#ueditor_0", chromedp.ByID),
		chromedp.SendKeys(`.input-box input`, article.Title, chromedp.ByQuery),
		chromedp.Evaluate(js, &res),
		chromedp.Evaluate(`document.querySelector(".cover-radio-group label:nth-child(3)").click()`, &res),
		chromedp.Click(`.ant-select-arrow`, chromedp.ByQuery),
		chromedp.Click(fmt.Sprintf(`.ant-select-dropdown-menu li:nth-child(%d)`, ty), chromedp.ByQuery),
		//chromedp.SendKeys(`.tags-container input`, "", chromedp.ByQuery),
		chromedp.Sleep(time.Second * 5),
		chromedp.Click(`.op-publish`, chromedp.ByQuery),
		chromedp.Sleep(time.Second * 2),
	}
}

func pubVideo(ck string, ty int, path string, imagePath string, title string, tag string) chromedp.Tasks {
	res := []byte{}

	return chromedp.Tasks{
		utils.ActionCookies(`.baidu.com`, ck),
		chromedp.Navigate(`http://baijiahao.baidu.com/builder/rc/edit/?type=video`),
		chromedp.WaitEvent(cdproto.EventPageLoadEventFired),
		chromedp.SendKeys(`.input-box .ant-input`, title, chromedp.ByQuery),
		chromedp.SendKeys(`desc`, title, chromedp.ByID),
		chromedp.SendKeys(`.webuploader-element-invisible`, utils.AbsolutePath(path), chromedp.ByQuery),

		chromedp.SendKeys(`.tags-container input`, tag+"  \r", chromedp.ByQuery),
		//选择分类
		chromedp.Click(`.client_components_selectNew div:nth-child(1)`, chromedp.ByQuery),
		chromedp.Click(fmt.Sprintf(`.ant-select-dropdown-menu li:nth-child(%d)`, ty), chromedp.ByQuery),
		//上传封面
		chromedp.Click(`.container`, chromedp.ByQuery),
		chromedp.Evaluate(`document.querySelector(".ant-upload-select span input").style = ""`, &res),
		chromedp.SendKeys(`.ant-upload-select span input`, utils.AbsolutePath(imagePath), chromedp.ByQuery),
		chromedp.Sleep(time.Second * 3),
		chromedp.Click(`.ant-modal-footer div button:nth-child(2)`, chromedp.ByQuery),

		chromedp.WaitVisible(`.video-result-desc-text`, chromedp.ByQuery),
		chromedp.Click(`.op-publish`, chromedp.ByQuery),
		chromedp.Sleep(time.Second * 2),
	}
}

func getArticle(u string) (FeedArticle, error) {
	url := `http://127.0.0.1:3333/article/feed`
	feedArticle := FeedArticle{}
	if err := utils.Get(url).Param("url", u).ToJSON(&feedArticle); err != nil {
		return feedArticle, err
	}
	return feedArticle, nil
}
